package top.hkyzf.study.leetcode.tree;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author 朱峰
 * @date 2022-2-19 10:31
 */
public class 二叉树的中序遍历_94 {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, result);
        return result;
    }

    private void dfs(TreeNode root, List<Integer> result) {
        if (root == null) {
            return ;
        }
        dfs(root.left, result);
        result.add(root.val);
        dfs(root.right, result);
    }

    /**
     * 方案二：迭代，中序遍历 左中右
     * @param root 根节点
     * @return 遍历结果
     */
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) {
            return null;
        }
        TreeNode cur = root;
        while (!stack.empty() || cur != null) {
            // 先遍历完左子树
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 最左边节点
            TreeNode node = stack.pop();
            result.add(node.val);

            // 遍历右边节点
            if (node.right != null) {
                cur = node.right;
            }
        }
        return result;
    }

    @Test
    public void testInorderTraversal () {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        node1.left = node2;
        root.right = node1;
        System.out.println(inorderTraversal1(root));
    }
}
